package cn.llyong.rpc.client.consumer;

import cn.llyong.rpc.common.discovery.ServiceDiscovery;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import cn.llyong.rpc.client.annotation.RpcReference;
import java.util.Map;

/**
 * @description: 
 * @author: llyong
 * @date: 2020年07月01日 19:45
 */
public class RpcConsumer implements ApplicationContextAware, InitializingBean {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private ServiceDiscovery serviceDiscovery;

    private ApplicationContext context;

    @Override
    public void afterPropertiesSet() throws Exception {
        Map<String, Object> beans = context.getBeansWithAnnotation(RpcReference.class);
        for (Object bean : beans.values()) {
            Class<?>[] interfaces = bean.getClass().getInterfaces();
            for (Class<?> clazz : interfaces) {
                RpcReference rpcReference = clazz.getAnnotation(RpcReference.class);

                serviceDiscovery.discovery(rpcReference.appName());
            }
        }
        logger.info("消费者订阅成功！！！");
    }

    @Override
    public void setApplicationContext(ApplicationContext context) throws BeansException {
        this.context = context;
    }
}
